import os
import random
import sqlite3
import db
import pandas as pd

def InitBook():
    BookDb = db.DBOperate("dictionary.db")
    TableName = BookDb.Query("SELECT name FROM sqlite_master where type='table' order by name;")
    frame = pd.DataFrame(pd.read_csv("data/counter.csv"))
    frame.set_index(["0"], inplace=True)
    return TableName, frame, BookDb

def DataAnalys(frame, user):
    counter = [0, 0, 0, 0, 0]
    for key, value in dict(frame[user]).items():
        right, error, All = map(int, value.split(";"))
        proficien = "还没背过"
        if All > 0:
            rate = right / All
            if rate > 0.85:
                proficien = "掌握"
                counter[0] += 1
            elif rate > 0.5:
                proficien = "逐渐掌握"
                counter[1] += 1
            elif rate > 0.25:
                proficien = "需要加强"
                counter[2] += 1
            else:
                proficien = "熟练度不高"
                counter[3] += 1
            print("单词: {} 评价：{}\n \t\t正确数：{}，错误数：{}，"
                  "默写次数：{}".format(key, proficien, right, error, All))
        else:
            print("单词: {} 评价：还没背诵过".format(key))
            counter[4] += 1

class Book:
    def __init__(self, user):
        self.Name, self.__frame, self.__DB = InitBook()
        self.Name = list(self.Name)
        self.user = user
        self.__WordList = None
        self.__RList, self.__EList = [], []

    def SearchWord(self, tableName, word):
        return self.__DB.Query(f"SELECT * FROM {tableName} WHERE WORD = '{word}';")[0]

    def AlterWord(self, tableName,  Column, word, newWord,):
        return self.__DB.defaultSQL(f"UPDATE {tableName} SET {word} = '{newWord}' WHERE {Column} = '{word}';")

    def GetAlpha(self, tableName, num):

        WordList = self.__DB.Query(f"SELECT * FROM {tableName}")
        self.__WordList = []
        while len(self.__WordList) < num:
            choose = random.choice(WordList)
            if choose not in self.__WordList:
                self.__WordList.append(choose)
        return self.__WordList


    def Counter(self, word, user, jug):
        columnName = self.__frame.columns.tolist()
        if user not in columnName:
            columnName.append(user)
            self.__frame = self.__frame.reindex(columnName)
        try:
            right, error, All = map(int, self.__frame.loc[word, user].split(";"))
        except:
            self.__frame.loc[word] = '0;0;0'
            right, error, All = map(int, self.__frame.loc[word, user].split(";"))

        if jug:
            right += 1
        else:
            error += 1
        All += 1
        self.__frame.loc[word, user] = "{};{};{}".format(right, error, All)

    def CN_To_EN(self, num: int):

        for _ in range(num):
            self.__word = self.randomWord()
            print(f"第{_ + 1}题: 请拼写 {self.__word[2]} 的英文 ")
            fill = input("请输入你的答案:> ")
            print(fill, self.__word[0])
            if fill == self.__word[0]:
                print("回答正确！")
                self.__RList.append(self.__word[0])
                self.__WordList.remove(self.__word)

                self.Counter(self.__word[0], self.user, 1)
            else:
                print("回答错误! 继续加油哦！")
                self.__EList.append(self.__word[0])
                self.Counter(self.__word[0], self.user, 0)

        else:
            print(f"答题结束!! 本次共默写{num}个单词，其中:\n "
                  f"正确数为: {len(self.__RList)}, 错题数为: {len(self.__EList)}")
            if len(self.__RList) == num:
                print("恭喜你，本次完成全对哦！！继续努力")

    def randomWord(self):
        return random.choice(self.__WordList)

    def EN_To_CN(self, num: int):
        for _ in range(num):
            self.__word, Options = self.randomChoseList()
            print(f"第{_ + 1}题: 请输入 {self.__word[0]} 的中文意思: ")
            print(f"\t A、{Options[0][2]}; \t B、{Options[1][2]};"
                  f"\t C、{Options[2][2]}; \t D、{Options[3][2]};")
            temp = {"A": 0, "B": 1, "C": 2, "D": 3}

            while 1:
                choose = input("请输入你的答案:> ").strip().upper()
                try:
                    print(Options[temp[choose]], self.__word)
                    if Options[temp[choose]] == self.__word:
                        print("回答正确！！")
                        self.__RList.append(self.__word)
                        self.__WordList.remove(self.__word)
                        self.Counter(self.__word[0], self.user, 1)
                    else:
                        print("回答错误！！")
                        self.__EList.append(self.__word)
                        self.Counter(self.__word[0], self.user, 1)

                    break
                except KeyError:
                    print("输入错误，请输入正确选项！！")
                    continue
        else:
            print(f"答题结束!! 本次共默写{num}个单词，其中:\n "
                  f"正确数为: {len(self.__RList)}, 错题数为: {len(self.__EList)}")
            if len(self.__RList) == num:
                print("恭喜你，本次完成全对哦！！继续努力")

    def randomChoseList(self, ):
        problemSet = []
        if len(self.__WordList) <= 4:
            temp = self.__WordList + self.__RList + self.__EList
            [problemSet.append(random.choice(temp)) for _ in range(4)]
            return random.choice(self.__WordList), problemSet
        while len(problemSet) <= 4:
            choice = random.choice(self.__WordList)
            if choice not in problemSet:
                problemSet.append(random.choice(self.__WordList))
        return random.choice(problemSet), problemSet


    
    def GetFrame(self):
        return self.__frame


def SecondaryMenu(table):
    print("=========== 请选择单词本 =================")
    for count, name in enumerate(table):
        print(f"      \t{count + 1}、 {''.join(name)}")

    return table[int(input("请选择单词本:> ").strip()) - 1]

def MainMenu():
    print("""
            ===========================================
                        欢迎来到单词默写系统
                            1、单词默写 (看释义，写单词)
                            2、背诵单词 (看单词，选释义)
                            3、搜索单词
                            4、修改单词
                            5、数据统计
                            0、退出
            ===========================================     
            """)
    while True:
        option = input("请选择你的功能：").strip()
        if option == "1":
            return 1
        elif option == "2":
            return 2
        elif option == "3":
            return 3
        elif option == 4:
            return 4
        elif option == 5:
            return 5
        elif option == "0":
            return 0
        else:
            print("输入错误，请重新输入")

class Main:
    def __init__(self, user):
        self.__book = Book(user)
        self.user = user
        self.__oprating = False

    def Option(self):
        mode = MainMenu()
        if mode == 1:
            self.Writer(mode)
        elif mode == 2:
            self.Writer(mode)
        elif mode == 3:
            self.Search()
        elif mode == 4:
            self.Alter()
        elif mode == 5:
            DataAnalys(frame=pd.DataFrame(pd.read_csv("data/counter.csv")),
                       user=self.user)
        elif mode == 0:
            self.__book.GetFrame().to_csv("data/counter.csv")
            if self.__oprating:
                return 0
            else:
                return 1

    def Writer(self, mode):
        choose = SecondaryMenu(self.__book.Name)
        count = int(input("请输入本次默写单词任务量:> "))
        WordBook = self.__book.GetAlpha(choose[0], count)
        print("本次默写的单词内容有:>")

        for index in range(len(WordBook)):
            print(WordBook[index])

        else:
            print("\n")
        input("按任意键开始背单词......")
        os.system("cls")
        print("\n")

        if mode == 1:
            self.__book.CN_To_EN(count)
        elif mode == 2:
            self.__book.EN_To_CN(count)
        self.__oprating = True

    def Search(self):
        table = input("请输入要查询的单词表:> ").strip()
        word = input("请输入要查找的单词:> ").strip()
        try:
            print(self.__book.SearchWord(table, word))
        except sqlite3.OperationalError:
            print("查找数据表错误！！")
        except IndexError:
            print("没有这个单词！！")

    def Alter(self):
        try:
            temp = {"单词":"WORD", "词性":"NATURE", "中文":"CHINESE"}
            self.__book.AlterWord(input("请输入要修改的单词表:> ").strip(),
                                  temp[input("请输入修改的的数据类型 单词? 词性? 中文?:> ").strip()],
                                  input("请输入要修改的内容:> ").strip(),
                                  input("请输入修改新的内容:> ").strip(),
                                  )
        except sqlite3.OperationalError or KeyError:
            print("输入的数据有误！！")
